# Appendix C
# Santiago Lopez-Cariboni, 2022. "Political Regimes and Informal Social Insurance", Comparative Political Studies.


# ---- wd ----
wd <- 'replication_materials' 
setwd(wd)

# ---- packages ----
pkgs <- c("data.table", "foreign", 'panelView', 'fect', "lubridate", 
    "ggplot2", "dplyr", "mFilter", "texreg", "AER", "xts", "interflex", "gridExtra")
suppressPackageStartupMessages(sapply(pkgs,require,character.only=T))
# Plot the effects (use Johannes Karreth's function: https://github.com/jkarreth/JKmisc/blob/master/ggintfun.R)
# devtools::source_url("https://raw.githubusercontent.com/jkarreth/JKmisc/master/ggintfun.R")
source('code/functions/ggintfun.R')
# Function for time Lags
source('code/functions/lagpanel.R')


# ---- data ----
dt <- fread('data/dt_replication.csv')
dt <- dt[LDC==1, ]


# ---- Figure D.1 ----
Z <- c("l.outgap.tdl", "l.capacity", "l.imports", "l.exports", "l.pop", "l.gdp.pcap", "l.elec.cons.pc")
linearity_optimal <- interflex(Y = "outgap.tdl", D = "democracy", X = "l.outgap.gdp.hamilton", Z = Z, data = dt, estimator = "kernel", FE = c("iso3c","year"), cl = "iso3c", CI = TRUE, theme.bw = TRUE, na.rm = TRUE) 
linearity_bw2 <- interflex(Y = "outgap.tdl", D = "democracy", X = "l.outgap.gdp.hamilton", Z = "l.outgap.tdl", data = dt, estimator = "kernel", FE = c("iso3c","year"), cl = "iso3c", CI = TRUE, theme.bw = TRUE, na.rm = TRUE, bw = 2) 
linearity_bw06 <- interflex(Y = "outgap.tdl", D = "democracy", X = "l.outgap.gdp.hamilton", Z = "l.outgap.tdl", data = dt, estimator = "kernel", FE = c("iso3c","year"), cl = "iso3c", CI = TRUE, theme.bw = TRUE, na.rm = TRUE, bw = .6) 
ylab = "Marginal Effect of Democracy on T&D Losses"
xlab = "GDP Outpug Gap"
ylim = c(-.60, .6)

pdf("figures/OA/D1_linearity.pdf", , width = 8, height = 6)
grid.arrange(plot(linearity_optimal, main = "Optimal bandwith", ylab = ylab, xlab = xlab, ylim = ylim), 
    plot(linearity_bw2, main = "Bandwith = 2", ylab = "", xlab = xlab, ylim = ylim), 
    plot(linearity_bw06, main = "Bandwith = 0.6", ylab = "", xlab = xlab, ylim = ylim), 
    ncol=3)
dev.off()

